<script setup lang="ts">
import { ref, getCurrentInstance, defineModel, computed, watch, shallowRef } from "vue"
import { message } from 'ant-design-vue'
import * as types from "../types"
const model = defineModel<string>()
const ins = getCurrentInstance()!
const open = ref(false)
const isNullable = ref(false)
const data = shallowRef<types.model | null>(null)
const options = computed(() => {
    let data = ins.appContext.config.globalProperties.$model
    let res: { label: string, value: string }[] = [{ label: '请选择', value: '-' }, { label: 'any', value: 'any' }]
    let arr = Object.keys(data).sort()
    for (let i of arr) {
        res.push({
            label: i,
            value: `$model/${i}`
        })
    }
    return res
})
function showDetail() {
    if (!tplValue.value.startsWith('$model')) {
        message.warn('这不是模板！')
        return
    }
    open.value = true
    data.value = ins.appContext.config.globalProperties.$model[tplValue.value.substring(7)]
}
function closeDetail() {
    open.value = false
    data.value = null
}
const tplValue = ref('')
const doUpdate = () => {
    model.value = tplValue.value + (isNullable.value ? '?' : '')
}
watch(model, () => {
    let m = model.value || ""
    if (m.endsWith('?')) {
        isNullable.value = true
        tplValue.value = m.slice(0, - 1)
    } else {
        isNullable.value = false
        tplValue.value = m
    }
}, { immediate: true })
</script>
<template>
    <div>
        <a-input-group compact>
            <a-switch v-model:checked="isNullable" checked-children="可空" un-checked-children="非空" @change="doUpdate"
                style="height: 32px;" />
            <a-select style="width: 80%;" v-model:value="tplValue" :options="options" :showSearch="true"
                @change="doUpdate">
                <template #suffixIcon>
                    <InfoCircleOutlined @click="showDetail" />
                </template>
            </a-select>
        </a-input-group>
        <a-modal v-model:open="open" title="详情" width="800px">
            <ModelObj v-if="data" v-model="data" readonly />
            <template #footer>
                <a-button type="primary" @click="closeDetail">确定</a-button>
            </template>
        </a-modal>
    </div>
</template>
<style></style>